package main

import "fmt"

type SparseArrayItem struct {
	Row int
	Col int
	Val int
}

var emptyVal int = 0

func init() {
	// 1、先创建一个原始数组
	var chessMap [11][11]int
	chessMap[1][2] = 1 // 黑子
	chessMap[2][3] = 2 // 白子
	// 2、转成稀疏数组
	// 思路：遍历chessMap数组，判断当前元素是否为默认值，若不是则将该元素的当前索引记作列数、当前子数组的索引记作行，当前原始记作值记录下来
	formatSparseArray := FormatSparseArray(chessMap, emptyVal)
	fmt.Printf("FormatSparseArray：%+v", formatSparseArray)
	// 将稀疏数组复原
	originalArray := RestoreOriginalArray(formatSparseArray, emptyVal)
	fmt.Printf("RestoreOriginalArray：%+v", originalArray)
}

// 转为稀疏数组
func FormatSparseArray(data [11][11]int, emptyVal int) []SparseArrayItem {
	result := []SparseArrayItem{
		{Row: 11, Col: 11, Val: 0},
	}
	for x, datum := range data {
		for y, i := range datum {
			if i != emptyVal {
				result = append(result, SparseArrayItem{
					Row: x,
					Col: y,
					Val: i,
				})
			}
		}
	}
	return result
}

// 恢复原始数组
func RestoreOriginalArray(data []SparseArrayItem, emptyVal int) [11][11]int {
	var chessMap [11][11]int
	for x, ints := range chessMap {
		for y, _ := range ints {
			chessMap[x][y] = emptyVal
		}
	}
	for _, datum := range data {
		if datum.Val == emptyVal {
			continue
		}
		chessMap[datum.Row][datum.Col] = datum.Val
	}
	return chessMap
}
